package qs.openxt.libs.plugins;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import qs.openxt.libs.R;
import qs.openxt.libs.fragment.ConfirmDialogListener;
import qs.openxt.libs.record.QTRecordActivity;
import qs.openxt.libs.remoting.ConvertAudioRecord;
import qs.openxt.libs.remoting.Upload;
import qs.openxt.libs.util.ActivityUtil;
import qs.openxt.libs.util.JSONUtil;
import qs.openxt.libs.util.StringUtil;

/**
 * 录音
 * @author 颖杰_2
 *
 */
public class RecordPlugins extends CordovaPlugin{
	private CallbackContext callbackContext;
	public static final int RETURNTYPE_VOICE = 1;
	private String url = null;
	private Object data = null;
    private boolean showConfirm = true;
	
	private Handler mHandler = new Handler() {
		public void handleMessage(final Message msg) {
			switch (msg.what) {
				case 1:{
					callbackContext.success((String)msg.obj);
					break;
				}
				case 2:{
					doConvert((String)msg.obj);
					break;
				}
				case 3:{
					doUpload((String)msg.obj);
					break;
				}
				case 4:{
					Toast.makeText(cordova.getActivity(), "文件上传失败", Toast.LENGTH_SHORT).show();
					break;
				}
                case 5:{
                    doC((String)msg.obj);
                    break;
                }
			default:
				break;
			}
		};
	};
	
	public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
		this.callbackContext = callbackContext;
		if ("doStartRecordApp".equals(action)) {
			if(!ActivityUtil.isNetworkAvailable(cordova.getActivity())){
				Toast.makeText(cordova.getActivity(), cordova.getActivity().getString(R.string.isNetworkAvailable), Toast.LENGTH_LONG).show();
				return false;
			}
			url = args.optString(0);
			data = args.opt(2);
            showConfirm = "false".equals(args.optString(3)) ? false : true;
			try {
				Intent intent = new Intent();
				intent.setClass(cordova.getActivity(), QTRecordActivity.class);
				intent.putExtra(QTRecordActivity.AUDIO_TIME, args.optString(1));
				cordova.startActivityForResult(RecordPlugins.this, intent, RETURNTYPE_VOICE);
			} catch (Exception e) {
			}
			return true;
		}
		return false;
	}
	
	public void onActivityResult(final int requestCode, final int resultCode, final Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		
		if (requestCode == RETURNTYPE_VOICE && resultCode == Activity.RESULT_OK) {
			String path = intent.getExtras().getString("path");
			
			Message message = new Message();
			message.what = 2;
			message.obj = path;
			mHandler.sendMessage(message);
		}
	}
	
	private void doConvert(final String path){
		try {
			ConvertAudioRecord convertAudioRecord = new ConvertAudioRecord(cordova.getActivity(), new ConvertAudioRecord.OnActionListener() {
				@Override
				public void onActionCompleted(final String reVal) {
					Message message = new Message();
					message.what = 5;
					message.obj = reVal;
					mHandler.sendMessage(message);
				}
			});
			convertAudioRecord.doConvert(path);
		} catch (Exception e) {
		}
	}

    private void doC(final String path){
        if(showConfirm){
            ActivityUtil.showConfirmDialog(cordova.getActivity(), "立即上传录音文件吗？", "确认", "取消", new ConfirmDialogListener() {
                @Override
                public void onOK() {
                    Message message = new Message();
                    message.what = 3;
                    message.obj = path;
                    mHandler.sendMessage(message);
                }

                @Override
                public void onCancel() {//返回本地地址
                    com.alibaba.fastjson.JSONArray array = new com.alibaba.fastjson.JSONArray();
                    array.add(path);
                    Message message = new Message();
                    message.what = 1;
                    message.obj = array.toString();
                    mHandler.sendMessage(message);
                }
            });
        }else{
            /*
            Message message = new Message();
            message.what = 3;
            message.obj = path;
            mHandler.sendMessage(message);*/
            com.alibaba.fastjson.JSONArray array = new com.alibaba.fastjson.JSONArray();
            array.add(path);
            Message message = new Message();
            message.what = 1;
            message.obj = array.toString();
            mHandler.sendMessage(message);
        }
    }
	
	private void doUpload(final String path){
		try {
			com.alibaba.fastjson.JSONObject params = new com.alibaba.fastjson.JSONObject();
			params.put("file", path);
			params.put("url", url);
			Object val = data;
			if (val != null) {
				if (val instanceof JSONObject) {
					params.put("param", JSONUtil.toJSON((JSONObject) val));
				} else if (!StringUtil.isNull(val)) {
					String[] split = val.toString().split("\\&");
					if (split.length > 1) {
						JSONObject param = new JSONObject();
						for (int i = 0; i < split.length; i++) {
							String[] $split = split[i].split("\\=");
							if ($split.length == 2)
								param.put($split[0], $split[1]);
						}
						params.put("param", param);
					}
				}
			}

			Upload upload = new Upload(cordova.getActivity(), new Upload.OnActionListener() {
				@Override
				public void onActionCompleted(final String reVal) {
					Message message = new Message();
					message.what = 1;
					message.obj = reVal;
					mHandler.sendMessage(message);
					new File(path).delete();
				}

				@Override
				public void onActionError() {
					Message message = new Message();
					message.what = 4;
					mHandler.sendMessage(message);
					new File(path).delete();
				}
			});
			upload.doRequest(params);
		} catch (Exception e) {
		}
	}
}
